import { useDeployProvider } from "../deploymentProvider";
import { useK8SApi } from "@/views/domain/kubeHud/api/k8s/k8s";
import type { Deployment, Pod } from "@/views/domain/kubeHud/api/k8s/types";
import { objectToString } from "@/views/domain/kubeHud/utils";
import { onMounted, ref } from "vue";

export const useDeployDetailsProvider = () => {
  const { deployProvider, route } = useDeployProvider();
  const { podRepo, deploymentRepo } = useK8SApi();

  const deployDetails = ref<Deployment>();
  const deployPods = ref<Pod[]>([]);

  const reloadDeployDetails = async (
    namespace?: string,
    name?: string
  ): Promise<Deployment | undefined> => {
    if (namespace && name) {
      const { data } = await deploymentRepo.getDeploymentDetail({
        namespace,
        name
      });
      return data;
    }
  };

  const reloadDeployPods = async (
    namespace?: string,
    selector?: { [key: string]: string }
  ): Promise<Pod[] | undefined> => {
    if (namespace && selector) {
      const { data } = await podRepo.getPodList({
        namespace,
        labelSelector: objectToString(selector)
      });
      return data.items;
    }
  };

  const _reloadDeployFullDetails = async (
    namespace?: string,
    name?: string
  ) => {
    deployDetails.value = await reloadDeployDetails(namespace, name);
    if (!deployDetails.value) return;

    deployPods.value = await reloadDeployPods(
      namespace,
      deployDetails.value.spec?.selector?.matchLabels
    );
  };

  // 根据路由参数重载
  const reloadFromRoute = async () => {
    const { namespace, name } = route.query;
    return deployProvider.loadingWrapper(_reloadDeployFullDetails, [
      namespace,
      name
    ]);
  };

  // onMounted(reloadFromRoute);
  onMounted(reloadFromRoute);

  return {
    loading: deployProvider.loading,
    route,
    deployDetails,
    deployPods,
    // reload
    reloadDeployFullInfo: (ns?: string, name?: string): Promise<void> => {
      return deployProvider.loadingWrapper(_reloadDeployFullDetails, [
        ns,
        name
      ]);
    }
  };
};
